<template>
  <div id="FormDialog">
    <PeopleSelect
      ref="peopleSelect"
      :type="'multiple'"
      :isCheck="true"
      :open="peopleOpen"
      @cancel="peopleOpen = false"
      @submit="submitPeople"
    ></PeopleSelect>
    <el-row>
      <el-col :span="24" class="margin_col">
        <div class="always_handerOne">
          <div class="always_hander"></div>
          <div class="always_title">
            {{ title ? `${title}` : "查评事件表单" }}
          </div>
        </div>
      </el-col>
      <el-col :span="24" class="margin_col">
        <div class="always_handerOne1">
          <el-collapse v-model="activeNames">
            <el-collapse-item name="2">
              <template slot="title">
                <div class="always_title1">
                  <div></div>
                  基本信息
                </div>
              </template>
              <el-form
                :model="formData"
                ref="vForm"
                :rules="rules"
                label-position="center"
                label-width="120px"
                size="medium"
                style="display: flex; justify-content: flex-start"
              >
                <el-form-item label="事件标题" prop="eventTitle">
                  <el-input
                    v-model="formData.eventTitle"
                    type="text"
                    clearable
                    :size="medium"
                    placeholder="请输入内容"
                    :disabled="ckDisabled"
                  ></el-input>
                </el-form-item>
                <el-form-item label="评审类型" prop="reviewClassify">
                  <el-select
                    v-model="formData.reviewClassify"
                    class="full-width-input"
                    clearable
                    :size="medium"
                    @change="classifyChange"
                    :disabled="ckDisabled"
                  >
                    <el-option
                      v-for="dict in dict.type.sys_review_classify"
                      :key="dict.value"
                      :label="dict.label"
                      :value="{ value: dict.value, label: dict.label }"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="受评单位" prop="reviewUnit">
                  <el-select
                    filterable
                    clearable
                    v-model="formData.reviewUnit"
                    class="full-width-input"
                    :size="medium"
                    :disabled="ckDisabled"
                  >
                    <!-- <el-option
                      v-for="option in deptOptions"
                      :key="option.value"
                      :label="option.label"
                      :value="option.value"
                    ></el-option> -->
                    <el-option-group
                      v-for="group in deptOptions"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.data"
                        :key="item.deptName"
                        :label="item.deptName"
                        :value="item.deptName"
                      >
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
                <el-form-item
                  label="起止日期"
                  prop="dateRange"
                  style="width: 60%"
                >
                  <el-date-picker
                    v-model="formData.dateRange"
                    style="width: 100%"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    :disabled="ckDisabled"
                  ></el-date-picker>
                </el-form-item>
                <el-form-item
                  label="查评内容设置"
                  prop="reviewContentSet"
                  style="width: 90%"
                >
                  <el-input
                    v-model="formData.reviewContentSet"
                    type="text"
                    clearable
                    :size="medium"
                    placeholder="请输入内容"
                    @focus="consoleHandle"
                    :disabled="cksDisabled"
                  ></el-input>
                </el-form-item>
                <el-form-item label="有效状态" prop="validStatus">
                  <el-checkbox
                    :checked="true"
                    v-model="formData.validStatus"
                    :disabled="ckDisabled"
                    >有效</el-checkbox
                  >
                </el-form-item>
              </el-form>
              <el-form
                :model="formDatas"
                ref="vFormFp"
                :rules="rulesFp"
                label-position="center"
                label-width="120px"
                size="medium"
                style="display: flex; justify-content: flex-start"
              >
                <el-form-item label="组长" class="required" prop="groupLeader">
                  <el-input
                    v-model="formDatas.groupLeader"
                    type="text"
                    clearable
                    :size="medium"
                    placeholder="请选择组长"
                    @focus="openGroupLeader"
                    :disabled="ckDisabled"
                  ></el-input>
                </el-form-item>
                <el-form-item label="组员" prop="member" style="width: 60%">
                  <el-input
                    v-model="formDatas.member"
                    type="text"
                    clearable
                    :size="medium"
                    @focus="openMember"
                    placeholder="请选择组员"
                    :disabled="ckDisabled"
                  ></el-input>
                </el-form-item>
              </el-form>
              <!-- </el-card> -->
              <template>
                <div>
                  <h3 style="font-weight: 600">任务分配</h3>
                  <el-button
                    size="small"
                    type="primary"
                    icon="el-icon-plus"
                    @click="addRow"
                    v-show="addLineShow"
                    style="margin-bottom: 12px"
                    >添加行</el-button
                  >
                  <el-button
                    size="small"
                    icon="el-icon-delete"
                    @click="removeRows"
                    v-show="addLineShow"
                    >删除行</el-button
                  >
                  <el-table
                    :data="tableDatas"
                    style="width: 100%"
                    border
                    row-key="id"
                    @selection-change="handleSelectionChange"
                  >
                    <el-table-column
                      type="selection"
                      width="55"
                      align="center"
                    />
                    <el-table-column label="序号" type="index" width="50" />
                    <el-table-column label="姓名" prop="member">
                      <template slot-scope="scope">
                        <el-select
                          v-model="scope.row.member"
                          class="full-width-input"
                          clearable
                          :size="medium"
                          :disabled="ckDisabled"
                          @change="handleChang(scope.row, memberList)"
                        >
                          <el-option
                            v-for="dict in memberList"
                            :key="dict.userId"
                            :label="dict.userName"
                            :value="dict.userName"
                          ></el-option>
                        </el-select>
                               
                      </template>
                           
                    </el-table-column>
                         
                    <el-table-column label="查评要素" prop="evaluationElements">
                             
                      <template slot-scope="scope">
                                 
                        <el-input
                          :size="medium"
                          v-model="scope.row.evaluationElements"
                          :disabled="cksDisabled"
                          @focus.stop="eventFocos(scope.row)"
                        ></el-input>
                               
                      </template>
                           
                    </el-table-column>
                       
                  </el-table>
                       
                </div>
              </template>
            </el-collapse-item>
          </el-collapse>
        </div>
      </el-col>
      <el-dialog
        :title="titles"
        :visible.sync="dialogVisible"
        width="50%"
        height="80%"
      >
        <el-checkbox
          v-model="checked"
          @change="handleCheckedTreeExpand($event, 'menu')"
          >展开/折叠</el-checkbox
        >
        <el-checkbox @change="handleCheckedTreeNodeAll($event, 'menu')"
          >全选/全不选</el-checkbox
        >
        <el-checkbox
          v-model="checked1"
          @change="handleCheckedTreeConnect($event, 'menu')"
          >父子联动</el-checkbox
        >
        <el-tree
          class="tree-border"
          :data="menuOptions"
          show-checkbox
          ref="menu"
          node-key="id"
          empty-text="加载中，请稍候"
          :props="defaultProps"
          :default-checked-keys="selectedIds"
          :check-strictly="!menuCheckStrictly"
          style="height: 100%; overflow: auto"
          default-expand-all="true"
          check-on-click-node="true"
          @check="handleMenuCheck"
        ></el-tree>
        <custom-buttons
          @back="dialogQx"
          @confirm="dialogQr"
          :handleShow="handleShow"
          confirmText="确定"
        ></custom-buttons>
      </el-dialog>
      <el-dialog
        :title="titles"
        :visible.sync="dialogVisibleCopy"
        width="50%"
        height="80%"
      >
        <el-tree
          class="tree-border"
          :data="menuOptionsCopy"
          show-checkbox
          ref="menuCopy"
          node-key="id"
          empty-text="加载中，请稍候"
          :props="defaultPropsCopy"
          :check-strictly="!menuCheckStrictlyCopy"
          :default-checked-keys="defaultCheckedKeys"
          default-expand-all="true"
          @check="handleMenuCheckCopy"
          style="height: 100%; overflow: auto"
          v-model="selectedNodes"
        ></el-tree>
        <custom-buttons
          @back="dialogQxCopy"
          @confirm="dialogQrCopy"
          :handleShow="handleShow"
          confirmText="确定"
        ></custom-buttons>
      </el-dialog>
      <el-col :span="24" class="margin_col">
        <div class="always_handerOne1">
          <custom-buttons
            @back="handleBack"
            @confirm="handleConfirm"
            @confirmzc="handleConfirmzc"
            :handleShow1="handleShow1"
            :handleShow="handleShow"
            :confirmText="confirmText"
          ></custom-buttons>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  listEvent,
  getEvent,
  delEvent,
  addEvent,
  queryDept,
  updateEvent,
  getEventsDataById,
  getTreeHx,
} from "../../../api/system/review/event";
import isEqual from "lodash/isEqual";
import PeopleSelect from "../../../components/Selection/index.vue";
import { listBasisAll, queryTreeData } from "../../../api/system/review/basis";
import CustomButtons from "@/components/CustomButton/CustomButton.vue";
export default {
  dicts: ["sys_normal_disable", "sys_review_classify"],
  components: { CustomButtons, PeopleSelect },
  props: {},
  data() {
    return {
      menu1: undefined,
      checked: true,
      checked1: true,
      selectedNodes: [],
      checkNodes: [],
      checkNodesCopy: [],
      placeholder2: "请选择时间",
      menuCheckStrictly: true,
      menuCheckStrictlyCopy: true,
      menuOptions: [],
      menuOptionsCopy: [],
      selectedMenuItems: [],
      dialogVisible: false,
      dialogVisibleCopy: false,
      isEdit: false,
      defaultCheckedKeys: [], // 存储默认选中的节点 ID 的数组
      deptOptions: [],
      //输入框的大小
      medium: "medium",
      activeNames: ["1", "2", "3"],
      fileList: [],
      tableData: [],
      handleShow1: true,
      handleShow: true,
      selectedIds: [],
      formData: {
        dateRange: [],
      },
      titles: "选择查评内容",
      title: "",
      rules: {
        reviewUnit: [
          { required: true, message: "受评单位不能为空", trigger: "change" },
        ],
        eventTitle: [
          { required: true, message: "事件标题不能为空", trigger: "change" },
        ],
        reviewClassify: [
          { required: true, message: "评审类型不能为空", trigger: "change" },
        ],
        startTime: [
          { required: true, message: "开始日期不能为空", trigger: "change" },
        ],
        endTime: [
          { required: true, message: "截至日期不能为空", trigger: "change" },
        ],
        dateRange: [
          { required: true, message: "截至日期不能为空", trigger: "change" },
        ],
        reviewContentSet: [
          {
            required: true,
            message: "查评内容设置不能为空",
            trigger: "change",
          },
        ],
      },
      rulesFp: {
        groupLeader: [
          { required: true, message: "组长不能为空", trigger: "change" },
        ],
        member: [
          { required: true, message: "组员不能为空", trigger: "change" },
        ],
      },
      defaultProps: {
        children: "children",
        label: "reviewProject",
      },
      defaultPropsCopy: {
        children: "children",
        label: "reviewProject",
        disabled: "disabled",
      },
      SORTOptions: [
        {
          label: "电力安全工器具",
          value: "1",
        },
        {
          label: "个人安全防护用品",
          value: 2,
        },
        {
          label: "仪器仪表",
          value: 3,
        },
      ],
      FILEFileList: [],
      FILEUploadHeaders: {},
      FILEUploadData: {},
      menuList: [],
      menuListCopy: [],
      queryParamsAll: {
        id: undefined,
        reviewClassify: undefined,
        reviewCode: undefined,
        reviewProject: undefined,
        reviewDate: undefined,
        reviewPerson: undefined,
        reviewPersonId: undefined,
        reviewObjInformation: undefined,
        reviewObjective: undefined,
        reviewStandard: undefined,
        reviewStandardScore: undefined,
        reviewOption: undefined,
        reviewBasic: undefined,
        reviewEndScore: undefined,
        reviewStatus: undefined,
        isControlPoint: undefined,
        remark: undefined,
        parentId: 0,
      },
      reviewSetIds: "",
      reviewSetNames: "",
      groupLeader: "",
      groupMembers: "",
      peopleOpen: false,
      checkData: "",
      memberList: [],
      tableDatas: [
        {
          id: 1,
          member: "",
          userid: "",
          evaluationElements: "",
          eventsid: "",
          standardScore: "",
          parentId: "",
          kzd: "",
        },
      ],
      formDatas: {
        id: undefined,
        reviewEvents: undefined, //查评事件
        groupName: undefined, //小组名称
        groupLeader: undefined, //小组组长
        groupLeaderCode: undefined, //组长编号
        member: undefined, //成员
        memberCode: undefined, //成员编号
        creationDate: undefined, //创建时间
        isDelete: undefined, //是否删除
        taskAllocation: undefined, //任务分配
        evaluationElements: "", //查评要素
        standardScore: undefined, //标准分
        reviewStatus: undefined, //评审状态
        reviewEventsId: undefined, //查评事件id
        evaluationElementsId: "", //查评事件id
      },
      contentListData: [],
      eventsData: [],
      setDatas: [],
      setHalfDatas: [],
      setCheckDatas: [],
      setCheckHalfDatas: [],
      currentRow: "",
      ckDisabled: false,
      cksDisabled: false,
      czxy: true,
      addLineShow: true,
      ids: [],
      checkedData: [],
      arrDatas: [],
      memberListzc: [],
      memberCodeListzc: [],
      confirmText: "下发",
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getTitle();
    this.handleUpdate();
    this.queryDept();
  },
  mounted() {},
  methods: {
    handleMenuCheck(selection, SelectedObj) {
      //selection  每次点击选中的数据
      this.formData.reviewHuixian = SelectedObj.checkedKeys.join(",");
      this.checkNodes = [
        ...this.$refs.menu.getCheckedNodes(),
        ...this.$refs.menu.getHalfCheckedNodes(),
      ];
      this.setCheckDatas = this.$refs.menu.getCheckedNodes();
      this.setCheckHalfDatas = this.$refs.menu.getHalfCheckedNodes();
      this.setDatas = SelectedObj.checkedNodes;
      this.setHalfDatas = SelectedObj.halfCheckedNodes;
      this.checkNodes = JSON.parse(JSON.stringify(this.checkNodes));
    },
    handleNodeClick(data) {
      console.log('----',data,this.$refs.menu);
    },
    getTreeNodeById(id) {
      // 遍历 menuOptions 数组
      for (const node of this.menuOptions) {
        // 如果当前节点的 id 匹配目标 id，则返回该节点对象
        if (node.id === id) {
          return node;
        }

        // 如果当前节点有子节点，则递归调用 getTreeNodeById 方法来查找子节点
        if (node.children && node.children.length > 0) {
          const childNode = this.getTreeNodeByIdFromChildren(node.children, id);
          if (childNode) {
            return childNode;
          }
        }
      }

      // 如果没有找到匹配的节点，则返回 null
      return null;
    },
    getTreeNodeByIdFromChildren(children, id) {
      for (const node of children) {
        if (node.id === id) {
          return node;
        }

        if (node.children && node.children.length > 0) {
          const childNode = this.getTreeNodeByIdFromChildren(node.children, id);
          if (childNode) {
            return childNode;
          }
        }
      }

      return null;
    },
    arrayToTree(data) {
      const result = [];
      const map = {};

      // 将所有节点存储在一个对象中，方便根据id查找
      data.forEach((item) => {
        item.children = [];
        map[item.id] = item;
      });

      data.forEach((item) => {
        const parent = map[item.parentId];

        if (parent) {
          parent.children.push(item);
        } else {
          result.push(item);
        }
      });

      return result;
    },
    findNodeById(treeData, id) {
      // 递归查找指定 ID 的节点
      for (let i = 0; i < treeData.length; i++) {
        const node = treeData[i];
        if (node.id === id) {
          return node;
        }
        if (node.children) {
          const result = this.findNodeById(node.children, id);
          if (result) {
            return result;
          }
        }
      }
      return null;
    },
    handleMenuCheckCopy(selection, SelectedObj) {
      this.checkNodesCopy = [
        ...this.$refs.menuCopy.getCheckedNodes(),
        ...this.$refs.menuCopy.getHalfCheckedNodes(),
      ];
      this.eventsData = SelectedObj.checkedNodes;
    },
    // // 所有菜单节点数据
    // getMenuAllCheckedKeys() {
    //   // 目前被选中的菜单节点
    //   let checkedKeys = this.$refs.menu.getCheckedKeys();
    //   // 获取name
    //   let checkedNodes = this.$refs.menu.getCheckedNodes();
    //   let names = checkedNodes.map((node) => node.reviewProject);
    //   // 半选中的菜单节点
    //   let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
    //   checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    //   let obj = {
    //     id: checkedKeys, //全选的key值数组
    //     name: names,
    //   };
    //   return obj;
    // },
    // getMenuAllCheckedKeysCopy() {
    //   // 目前被选中的菜单节点
    //
    //   let checkedKeys = this.$refs.menuCopy.getCheckedKeys();
    //   // 获取name
    //   let checkedNodes = this.$refs.menuCopy.getCheckedNodes();
    //   let names = checkedNodes.map((node) => node.reviewProject);
    //   // 半选中的菜单节点
    //   let halfCheckedKeys = this.$refs.menuCopy.getHalfCheckedKeys();
    //   checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
    //   let obj = {
    //     id: checkedKeys, //全选的key值数组
    //     name: names,
    //   };
    //   return obj;
    // },
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menu.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == "dept") {
        let treeList = this.deptOptions;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.dept.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    handleCheckedTreeNodeAll(value, type) {
      debugger
      if (type == "menu") {
        this.$refs.menu.setCheckedNodes(value ? this.menuOptions : []);
        this.checkNodes = this.$refs.menu.getCheckedNodes();
      } else if (type == "dept") {
        this.$refs.dept.setCheckedNodes(value ? this.deptOptions : []);
      }
    },
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.menuCheckStrictly = value ? true : false;
      } else if (type == "dept") {
        this.deptCheckStrictly = value ? true : false;
      }
    },
    handleChang(ins, val) {
      val.forEach((item) => {
        if (item.userName === ins.member) {
          ins.userid = item.userId;
        }
      });
    },
    eventFocos(row) {
      //获取element-ui el-tree组件的实例
      let elTreeInstance = this.$refs["menuCopy"];

      if (elTreeInstance != undefined) {
        if (this.eventsData.length == 0) {
          elTreeInstance.setCheckedKeys([]);
        }
      }
      //调用API中的clearSelection方法，清除所有选中数据
      this.currentRow = row;
      this.checkedData = [];
      const rowData = this.currentRow.eventsid.split(",");
      let mrxz = [];
      this.defaultCheckedKeys = [];
      
      for (let s = 0; s < rowData.length; s++) {
        const node = this.findNodeById(this.menuOptionsCopy, rowData[s]);

        if (node) {
          // 找到对应节点，并将 disabled 属性设置为 true
          this.$set(node, "disabled", false);
          this.defaultCheckedKeys.push(rowData[s]);
          // this.$set(node, 'default-checked-keys', rowData[s]);
        }
      }
      this.consoleHandleCopy();
    },
    //打开组长选择弹窗
    openGroupLeader() {
      this.checkData = "single";
      this.peopleOpen = true;
    },
    //打开组员选择弹窗
    openMember() {
      this.checkData = "multi";
      this.peopleOpen = true;
    },
    //选中人员后保存操作
    submitPeople(peopleList) {
      //判断是单选还是多选
      if (this.checkData == "single") {
        if (peopleList.length != 1) {
          return this.$message.warning("请选择一个人员");
        } else {
          this.formDatas.groupLeader = peopleList[0].userName;
          this.formDatas.groupLeaderCode = peopleList[0].userId;
        }
      } else if (this.checkData == "multi") {
        //将选中组员数据存入memberList中
        this.memberList = peopleList;
        if (peopleList.length < 1) {
          return this.$message.warning("请至少选择一个人员");
        } else {
          let member = "";
          let memberCode = "";
          for (let s = 0; s < peopleList.length; s++) {
            member += peopleList[s].userName + ",";
            memberCode += peopleList[s].userId + ",";
          }
          this.formDatas.member = member.substring(0, member.length - 1);
          this.formDatas.memberCode = memberCode.substring(
            0,
            memberCode.length - 1
          );
        }
      }
      this.peopleOpen = false;
    },
    addRow() {
      const newRow = {
        id: this.tableDatas.length + 1,
        member: "",
        age: 0,
        username: "",
        userid: "",
        evaluationElements: "",
        eventsid: "",
        standardScore: "",
      };
      this.tableDatas.push(newRow);
    },
    removeRows() {
      for (const row of this.ids) {
        const index = this.tableDatas.indexOf(row);
        if (index !== -1) {
          this.tableDatas.splice(index, 1);
        }
      }
      // 清空选中的行数据
      this.ids = [];
    },
    removeRow(index) {
      this.tableDatas.splice(index, 1);
    },
    rowClick(row) {
      this.queryParamsAll.parentId = row.id;
      this.getList(row);
    },
    rowClickCopy(row) {
      this.queryParamsAll.parentId = row.id;
      this.getList(row);
    },
    getList(row) {
      listBasisAll(this.queryParamsAll).then((response) => {
        if (row != "" && row != undefined) {
          row.children = this.handleTree(response, "id");
        } else {
          this.menuList = this.handleTree(response, "id");
        }
        this.basisList = response.rows;
        this.total = response.total;
      });
    },
    // handleClose(done) {
    //   this.$confirm("确认关闭？")
    //     .then((_) => {
    //       done();
    //     })
    //     .catch((_) => {});
    // },
    // handleCloseCopy(done) {
    //
    //   this.$confirm("确认关闭？")
    //     .then((_) => {
    //       const allData = this.eventsData;
    //       const tree = this.$refs.menuCopy;
    //       if(tree){
    //         const checkedKeys = tree.getCheckedKeys(); // 获取所有选中节点的 ID
    //           const nonDisabledCheckedKeys = checkedKeys.filter(key => {
    //             const node = tree.getNode(key);
    //             return node && !node.disabled; // 过滤掉禁用的节点
    //           });
    //         for(let s=0;s<nonDisabledCheckedKeys.length;s++){
    //           for(let a=0;a<this.eventsData.length;a++){
    //             if(nonDisabledCheckedKeys[s] == this.eventsData[a].id){
    //               this.checkedData.push(this.eventsData[a]);
    //             }
    //           }
    //         }
    //       }
    //       this.eventsData = this.checkedData
    //       for(let s = 0;s< this.eventsData.length;s++){
    //         //
    //         const fixedNodeId = this.eventsData[s].id; // 要禁止选中的固定 ID
    //         const node = this.findNodeById(this.menuOptionsCopy, fixedNodeId);
    //         if (node) {
    //           // 找到对应节点，并将 disabled 属性设置为 true
    //           this.$set(node, 'disabled', true);
    //         }
    //         //
    //       }
    //       this.eventsData = allData
    //       done();
    //     })
    //     .catch((_) => {});
    // },
    dialogQxCopy() {
      const allData = this.eventsData;
      const tree = this.$refs.menuCopy;
      if (tree) {
        const checkedKeys = tree.getCheckedKeys(); // 获取所有选中节点的 ID
        const nonDisabledCheckedKeys = checkedKeys.filter((key) => {
          const node = tree.getNode(key);
          return node && !node.disabled; // 过滤掉禁用的节点
        });
        for (let s = 0; s < nonDisabledCheckedKeys.length; s++) {
          for (let a = 0; a < this.eventsData.length; a++) {
            if (nonDisabledCheckedKeys[s] == this.eventsData[a].id) {
              this.checkedData.push(this.eventsData[a]);
            }
          }
        }
      }
      this.eventsData = this.checkedData;
      for (let s = 0; s < this.eventsData.length; s++) {
        //
        const fixedNodeId = this.eventsData[s].id; // 要禁止选中的固定 ID
        const node = this.findNodeById(this.menuOptionsCopy, fixedNodeId);
        if (node) {
          // 找到对应节点，并将 disabled 属性设置为 true
          this.$set(node, "disabled", true);
        }
        //
      }
      this.eventsData = allData;
      this.dialogVisibleCopy = false;
      this.dialogVisibleCopy = false;
    },
    dialogQrCopy(val) {
      const allData = this.eventsData;
      console.log(this.eventsData);
      if (this.eventsData.length == 0) {
        return this.$message.warning("请在做出变动后再点击保存且不可以为空");
      }
      const tree = this.$refs.menuCopy;
      if (tree) {
        const checkedKeys = tree.getCheckedKeys(); // 获取所有选中节点的 ID
        const nonDisabledCheckedKeys = checkedKeys.filter((key) => {
          const node = tree.getNode(key);
          return node && !node.disabled; // 过滤掉禁用的节点
        });
        for (let s = 0; s < nonDisabledCheckedKeys.length; s++) {
          for (let a = 0; a < this.eventsData.length; a++) {
            if (nonDisabledCheckedKeys[s] == this.eventsData[a].id) {
              this.checkedData.push(this.eventsData[a]);
            }
          }
        }
      }
      this.eventsData = this.checkedData;
      let names = "";
      let ids = "";
      let scores = "";
      let parentId = "";
      let kzds = "";
      for (let s = 0; s < this.eventsData.length; s++) {
        //
        const fixedNodeId = this.eventsData[s].id; // 要禁止选中的固定 ID
        const node = this.findNodeById(this.menuOptionsCopy, fixedNodeId);
        if (node) {
          // 找到对应节点，并将 disabled 属性设置为 true
          this.$set(node, "disabled", true);
        }
        //
        names += this.eventsData[s].reviewProject + ",";
        ids += this.eventsData[s].id + ",";
        if (
          this.eventsData[s].reviewStandardScore == null ||
          this.eventsData[s].reviewStandardScore == ""
        ) {
          this.eventsData[s].reviewStandardScore = "0";
        }
        kzds += this.eventsData[s].isControlPoint + ",";
        scores += this.eventsData[s].reviewStandardScore + ",";
        parentId += this.eventsData[s].parentId + ",";
      }
      this.currentRow.evaluationElements = names.substring(0, names.length - 1);
      this.currentRow.eventsid = ids.substring(0, ids.length - 1);
      this.currentRow.standardScore = scores.substring(0, scores.length - 1);
      this.currentRow.parentId = parentId.substring(0, parentId.length - 1);
      this.currentRow.kzd = kzds.substring(0, kzds.length - 1);
      this.eventsData = allData;
      this.dialogVisibleCopy = false;
    },
    dialogQx() {
      this.dialogVisible = false;
    },
    dialogQr(val) {
      // for(let s=0;s<this.setHalfDatas.length;s++){
      //   this.setDatas.push(this.setHalfDatas[s])
      // }
      // let treeDatas = this.handleTree(this.setDatas,"id");
      // this.menuOptionsCopy = treeDatas;

      this.checkNodes = JSON.parse(JSON.stringify(this.checkNodes));
      const treeData = this.handleTree(this.checkNodes, "id");
      this.menuOptionsCopy = treeData;
      if (this.checkNodes.length == 0) {
        return this.$message.warning("请在做出变动后再点击保存");
      }
      let names = "";
      let ids = "";
      for (let s = 0; s < this.checkNodes.length; s++) {
        names += this.checkNodes[s].reviewProject + ",";
        ids += this.checkNodes[s].id + ",";
      }
      names = names.substring(0, names.length - 1);
      ids = ids.substring(0, ids.length - 1);
      this.formData.reviewContentSet = names;
      this.formData.reviewContentSetId = ids;

      if (this.formData.reviewContentSet !== "") {
        this.dialogVisible = false;
      }
    },

    classifyChange() {
      this.queryParamsAll.reviewClassify = this.formData.reviewClassify.label;
      this.formData.reviewClassify = this.formData.reviewClassify.label;
      this.queryTreeDatas(this.formData.reviewClassify);
    },
    queryTreeDatas(reviewClassify) {
      let obj = { classify: reviewClassify };
      queryTreeData(obj).then((response) => {
        const map = {}; // 使用一个对象来存储每个节点
        const tree = []; // 最终的树形结构

        response.forEach((item) => {
          item.children = []; // 初始化 children 属性
          map[item.id] = item; // 使用 id 作为节点的唯一标识
        });
        this.menuOptions = this.handleTree(response, "id");
        // this.menuOptionsCopy = this.handleTree( response, "id")
        return null;
      });
    },
    recursiveQuery(arr) {
      let result = null;
      for (const item of arr) {
        if (item.children != null && item.children != undefined) {
          if (item.children && item.children.length > 0) {
            for (let s = 0; s < item.children.length; s++) {
              this.reviewSetIds += item.children[s].id + ",";
              this.reviewSetNames += item.children[s].reviewProject + ",";
            }
            result = this.recursiveQuery(item.children);
          }
        } else {
          this.reviewSetIds += item.id + ",";
          this.reviewSetNames += item.reviewProject + ",";
        }
      }
    },
    consoleHandleCopy() {
      this.menuListCopy = this.contentListData;
      // this.handleShow = false;
      this.dialogVisibleCopy = true;
    },
    consoleHandle() {
      if (this.formData.reviewClassify == null) {
        return this.$message.warning("请先选择评审类型");
      }

      this.dialogVisible = true;
    },
    getTitle() {
      const { ID, title } = this.$route.query;
      this.title = title;
    },
    handleBack() {
      window.history.back();
      // 执行返回逻辑
    },
    handleConfirm() {
      this.$refs["vFormFp"].validate((valid) => {});
      this.$refs["vForm"].validate((valid) => {
        this.formData.reviewStatus = "0";
        let endDatas = {
          formData: this.formData,
          tableDatas: this.tableDatas,
          leader: this.formDatas.groupLeader,
          leaderCode: this.formDatas.groupLeaderCode,
        };
        this.formData.createTime = null;
        this.formData.updateTime = null;
        for (let s = 0; s < this.tableDatas.length; s++) {
          if (
            this.tableDatas[s].userid == "" ||
            this.tableDatas[s].userid == null ||
            this.tableDatas[s].eventsid == "" ||
            this.tableDatas[s].eventsid == null
          ) {
            return this.$modal.msgWarning("任务分配不能为空");
          }
        }
        if (valid) {
          // this.loading = true;
          this.$modal.loading("保存中");
          this.formData.startTime = this.formData.dateRange[0];
          this.formData.endTime = this.formData.dateRange[1];
          delete this.formData.dateRange;
          if (this.formData.id !== undefined) {
            updateEvent(endDatas)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.$modal.closeLoading();
              })
              .finally(() => {
                this.$router.push("/review/reviewPrepare/reviewEvent");
                // this.buttonLoading = false
                this.$refs.formData.resetFields(); // 重置表单数据
                this.reset();
              });
          } else {
            addEvent(endDatas)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.$modal.closeLoading();
              })
              .finally(() => {
                // this.buttonLoading = false;
                this.$refs.vForm.resetFields(); // 重置表单数据
                this.$router.push("/review/reviewPrepare/reviewEvent");
                this.reset();
              });
          }
        }
      });
    },
    handleConfirmzc() {
      this.$refs["vFormFp"].validate((valid) => {
        this.$refs["vForm"].validate((valid) => {
          this.formData.reviewStatus = "1";
          let endDatas = {
            formData: this.formData,
            tableDatas: this.tableDatas,
            leader: this.formDatas.groupLeader,
            leaderCode: this.formDatas.groupLeaderCode,
          };
          this.formData.createTime = null;
          this.formData.updateTime = null;
          for (let s = 0; s < this.tableDatas.length; s++) {
            if (
              this.tableDatas[s].userid == "" ||
              this.tableDatas[s].userid == null ||
              this.tableDatas[s].eventsid == "" ||
              this.tableDatas[s].eventsid == null
            ) {
              return this.$modal.msgWarning("任务分配不能为空");
            }
          }
          if (valid) {
            // this.loading = true;
            this.$modal.loading("保存中");
            this.formData.startTime = this.formData.dateRange[0];
            this.formData.endTime = this.formData.dateRange[1];
            delete this.formData.dateRange;
            if (this.formData.id !== undefined) {
              updateEvent(endDatas)
                .then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.$modal.closeLoading();
                })
                .finally(() => {
                  this.$router.push("/review/reviewPrepare/reviewEvent");
                  // this.buttonLoading = false
                  this.$modal.closeLoading();

                  this.$refs.formData.resetFields(); // 重置表单数据
                  this.reset();
                });
            } else {
              addEvent(endDatas)
                .then((response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.$modal.closeLoading();
                })
                .finally(() => {
                  // this.buttonLoading = false;
                  this.$modal.closeLoading();

                  this.$refs.vForm.resetFields(); // 重置表单数据
                  this.$router.push("/review/reviewPrepare/reviewEvent");
                  this.reset();
                });
            }
          }
        });
      });
    },
    reset() {
      this.formData = {
        reviewUnit: undefined,
        eventTitle: undefined,
        reviewClassify: undefined,
        startTime: undefined,
        endTime: undefined,
        reviewContentSet: undefined,
        reviewMode: 1,
        reviewEventShows: undefined,
        validStatus: undefined,
        reviewContentSetId: undefined,
      };
    },
    submitForm() {},
    queryDept() {
      let name = this.$store.state.user.name;
      queryDept(name).then((row) => {
        console.log("row", row);
        let a = row.其他;
        let b = row.新能源;
        let c = row.水电;
        let d = row.火电;
        let arr = {
          label: "其他",
          data: a,
        };
        let arr2 = {
          label: "新能源",
          data: b,
        };
        let arr3 = {
          label: "水电",
          data: c,
        };
        let arr4 = {
          label: "火电",
          data: d,
        };
        this.deptOptions.push(arr, arr2, arr3, arr4);
        // this.deptOptions = [];
        //   row.forEach((item) => {
        //     this.deptOptions.push({
        //       "label" : item.deptName,
        //       "value" : item.deptName
        //     })
        //   })
      });
    },
    handleUpdate() {
      const { ID } = this.$route.query;
      this.reset();
      if (this.$route.query.flowId == 1 || this.$route.query.evalution == 1) {
        getEvent(ID).then((response) => {
          if (this.$route.query.evalution == 1) {
            this.handleShow1 = false;
            this.handleShow = false;
            this.ckDisabled = true;
            this.czxy = false;
            this.addLineShow = false;
          }
          if (response.data.reviewStatus == 0) {
            this.handleShow1 = false;
            this.handleShow = false;
            this.ckDisabled = true;
            this.czxy = false;
            this.addLineShow = false;
            response.data.dateRange = [];
            response.data.dateRange.push(new Date(response.data.startTime));
            response.data.dateRange.push(new Date(response.data.endTime));
            this.formData = response.data;
            const arrLiser = this.queryTreeDatas(this.formData.reviewClassify);
            let aas = {
              setId: response.data.reviewContentSetId,
            };
            getTreeHx(aas).then((res) => {
              console.log(res);
              const treeData = this.handleTree(res, "id");
              console.log(treeData);
              this.menuOptionsCopy = treeData;
            });
            // this.$refs.menu.setCheckedKeys([1369477636741484545,1369478523148914690]);
            if (response.code == 200) {
              let queryData = {
                id: this.$route.query.ID[0],
              };
              getEventsDataById(queryData).then((response) => {
                //组长回显
                this.formDatas.groupLeader = response[0].groupLeader;
                this.formDatas.groupLeaderCode = response[0].groupLeaderCode;
                //组员回显
                for (let s = 0; s < response.length; s++) {
                  this.memberListzc.push(response[s].member);
                  this.memberCodeListzc.push(response[s].memberCode);
                }
                this.memberListzc = [...new Set(this.memberListzc)];
                this.memberCodeListzc = [...new Set(this.memberCodeListzc)];
                let memberlists = "";
                let membercodelists = "";
                for (let a = 0; a < this.memberCodeListzc.length; a++) {
                  if (this.memberCodeListzc.length - a == 1) {
                    memberlists += this.memberListzc[a];
                    membercodelists += this.memberCodeListzc[a];
                  } else {
                    memberlists += this.memberListzc[a] + ",";
                    membercodelists += this.memberCodeListzc[a] + ",";
                  }
                }
                this.formDatas.member = memberlists;
                this.formDatas.memberCode = membercodelists;
                this.selectedIds = this.formData.reviewHuixian.split(",");
                let memberSp = this.formDatas.member.split(",");
                let memberCodeSp = this.formDatas.memberCode.split(",");
                let memberLsitsdata = [];
                for (let a = 0; a < memberSp.length; a++) {
                  memberLsitsdata.push({
                    userId: memberCodeSp[a],
                    userName: memberSp[a],
                  });
                }
                this.memberList = memberLsitsdata;

                //回显表单数据
                let obj = [];
                let nullPoint = [];
                for (let a = 0; a < response.length; a++) {
                  if (response[a].isContolPoint == "是") {
                    nullPoint.push(response[a]);
                  }
                }
                response = nullPoint;
                for (let a = 0; a < this.memberListzc.length; a++) {
                  let evaluationElements = "";
                  let eventsid = "";
                  let standardScore = "";
                  let parentId = "";
                  let kzds = "";
                  for (let s = 0; s < response.length; s++) {
                    if (this.memberListzc[a] == response[s].member) {
                      evaluationElements +=
                        response[s].evaluationElements + ",";
                      eventsid += response[s].evaluationElementsId + ",";
                      standardScore += response[s].standardScore + ",";
                      parentId += response[s].evaluationElementsParentId + ",";
                      kzds += response[s].isContolPoint + ",";
                    }
                  }
                  evaluationElements = evaluationElements.substring(
                    0,
                    evaluationElements.length - 1
                  );
                  eventsid = eventsid.substring(0, eventsid.length - 1);
                  standardScore = standardScore.substring(
                    0,
                    standardScore.length - 1
                  );
                  parentId = parentId.substring(0, parentId.length - 1);
                  kzds = kzds.substring(0, kzds.length - 1);
                  // const endstandardScore = standardScore.split(",")
                  obj.push({
                    evaluationElements: evaluationElements,
                    eventsid: eventsid,
                    member: this.memberListzc[a],
                    standardScore: standardScore,
                    userid: this.memberCodeListzc[a],
                    parentId: parentId,
                    kzd: kzds,
                  });
                }
                this.tableDatas = obj;
              });
            }
            this.loading = false;
            if (this.formData.reviewMode == "线下") {
              this.formData.reviewMode = 1;
            } else if (this.formData.reviewMode == "线上") {
              this.formData.reviewMode = 2;
            }
            if (this.formData.validStatus == "有效") {
              this.formData.validStatus = true;
            } else if (this.formData.reviewMode == "无效") {
              this.formData.validStatus = false;
            }
          } else if (response.data.reviewStatus == 1) {
            response.data.dateRange = [];
            response.data.dateRange.push(new Date(response.data.startTime));
            response.data.dateRange.push(new Date(response.data.endTime));
            this.formData = response.data;
            const arrLiser = this.queryTreeDatas(this.formData.reviewClassify);
            let aas = {
              setId: response.data.reviewContentSetId,
            };
            getTreeHx(aas).then((res) => {
              console.log(res);
              const treeData = this.handleTree(res, "id");
              console.log(treeData);
              this.menuOptionsCopy = treeData;
            });
            // this.$refs.menu.setCheckedKeys([1369477636741484545,1369478523148914690]);
            if (response.code == 200) {
              let queryData = {
                id: this.$route.query.ID[0],
              };
              getEventsDataById(queryData).then((response) => {
                //组长回显
                this.formDatas.groupLeader = response[0].groupLeader;
                this.formDatas.groupLeaderCode = response[0].groupLeaderCode;
                //组员回显
                for (let s = 0; s < response.length; s++) {
                  this.memberListzc.push(response[s].member);
                  this.memberCodeListzc.push(response[s].memberCode);
                }
                this.memberListzc = [...new Set(this.memberListzc)];
                this.memberCodeListzc = [...new Set(this.memberCodeListzc)];
                let memberlists = "";
                let membercodelists = "";
                for (let a = 0; a < this.memberCodeListzc.length; a++) {
                  if (this.memberCodeListzc.length - a == 1) {
                    memberlists += this.memberListzc[a];
                    membercodelists += this.memberCodeListzc[a];
                  } else {
                    memberlists += this.memberListzc[a] + ",";
                    membercodelists += this.memberCodeListzc[a] + ",";
                  }
                }
                this.formDatas.member = memberlists;
                this.formDatas.memberCode = membercodelists;
                this.selectedIds = this.formData.reviewHuixian.split(",");
                let memberSp = this.formDatas.member.split(",");
                let memberCodeSp = this.formDatas.memberCode.split(",");
                let memberLsitsdata = [];
                for (let a = 0; a < memberSp.length; a++) {
                  memberLsitsdata.push({
                    userId: memberCodeSp[a],
                    userName: memberSp[a],
                  });
                }
                this.memberList = memberLsitsdata;

                //回显表单数据
                let obj = [];
                let nullPoint = [];
                for (let a = 0; a < response.length; a++) {
                  if (response[a].isContolPoint == "是") {
                    nullPoint.push(response[a]);
                  }
                }
                response = nullPoint;
                for (let a = 0; a < this.memberListzc.length; a++) {
                  let evaluationElements = "";
                  let eventsid = "";
                  let standardScore = "";
                  let parentId = "";
                  let kzds = "";
                  for (let s = 0; s < response.length; s++) {
                    if (this.memberListzc[a] == response[s].member) {
                      evaluationElements +=
                        response[s].evaluationElements + ",";
                      eventsid += response[s].evaluationElementsId + ",";
                      standardScore += response[s].standardScore + ",";
                      parentId += response[s].evaluationElementsParentId + ",";
                      kzds += response[s].isContolPoint + ",";
                    }
                  }
                  evaluationElements = evaluationElements.substring(
                    0,
                    evaluationElements.length - 1
                  );
                  eventsid = eventsid.substring(0, eventsid.length - 1);
                  standardScore = standardScore.substring(
                    0,
                    standardScore.length - 1
                  );
                  parentId = parentId.substring(0, parentId.length - 1);
                  kzds = kzds.substring(0, kzds.length - 1);
                  // const endstandardScore = standardScore.split(",")
                  obj.push({
                    evaluationElements: evaluationElements,
                    eventsid: eventsid,
                    member: this.memberListzc[a],
                    standardScore: standardScore,
                    userid: this.memberCodeListzc[a],
                    parentId: parentId,
                    kzd: kzds,
                  });
                }
                this.tableDatas = obj;
              });
            }
            this.loading = false;
            if (this.formData.reviewMode == "线下") {
              this.formData.reviewMode = 1;
            } else if (this.formData.reviewMode == "线上") {
              this.formData.reviewMode = 2;
            }
            if (this.formData.validStatus == "有效") {
              this.formData.validStatus = true;
            } else if (this.formData.reviewMode == "无效") {
              this.formData.validStatus = false;
            }
          }
        });
      }
    },
    highlightNodes(treeData, targetIds) {
      // 遍历树的每个节点
      for (const node of treeData) {
        // 检查当前节点是否匹配目标ID
        if (targetIds.includes(node.id)) {
          // 如果匹配，则将节点标记为选中状态（例如添加一个 "highlight" 属性）
          node.highlight = true;
        }
        // 递归处理子节点
        if (node.children) {
          highlightNodes(node.children, targetIds);
        }
      }
    },
    resetForm() {
      this.$refs["vForm"].resetFields();
    },
    handleSuccess(response, file, fileList) {
      // 文件上传成功后，将文件信息添加到表格数据中
      this.fileList = fileList;
      this.tableData.push({
        name: file.name,
        size: (file.size / 1024).toFixed(2) + "KB",
        url: URL.createObjectURL(file.raw),
      });
    },
    handlePreview(file) {},
    handleRemove(file, fileList) {
      // 文件删除时，同时从表格数据中删除对应的文件信息
      this.fileList = fileList;
      this.tableData = this.tableData.filter((item) => item.name !== file.name);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning("只能上传不超过3个文件");
    },
    handleSelectionChange(selection) {
      this.ids = selection;
    },
  },
};
</script>

<style lang="scss" scoped>
.el_col {
  display: flex;
  justify-content: space-evenly;
  align-content: center;
}
.card-container {
  height: 80%; /* 设置容器的高度为 100% */
  display: flex;
  flex-direction: column;
}
.card-item {
  flex: 1; /* 平分容器的宽度 */
}
#FormDialog {
  height: 100%;
  display: flex;
  flex-wrap: nowrap;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden;
  ::v-deep.el-dialog__wrapper > .el-dialog {
    height: 80%;
  }
  ::v-deep.el-dialog__body {
    height: 84%;
  }
  ::v-deep.tree-border {
    margin-bottom: 10px;
  }
  ::v-deep.el-tree {
    .el-checkbox__inner {
      background: url("../../../assets/images/default.png");
      background-size: contain;
      border: none;
      border-radius: none;
      &:after {
        display: none;
      }
    }
    .is-indeterminate .el-checkbox__inner {
      background: url("../../../assets/images/indeterminate.png");
      background-size: contain;
      border: none;
      border-radius: none;
      &:after {
        display: none;
      }
    }
    .is-checked .el-checkbox__inner {
      background: url("../../../assets/images/checked.png");
      background-size: contain;
      border: none;
      border-radius: none;
      &:after {
        display: none;
      }
    }
    .is-disabled .el-checkbox__inner {
      background: url("../../../assets/images/disabled.png");
      background-size: contain;
      border: none;
      border-radius: none;
      &:after {
        display: none;
      }
    }
  }
}
.dialog-footer1 {
  width: 100%;
  height: 6vh;
  background: #ffffff;
  text-align: center;
  line-height: 6vh;
}
.el-card {
  margin-top: 10px;
}
.el-select {
  width: 100%;
}
.el-form {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
}
.el-form-item {
  width: 30%;
}
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
.el-form-item {
  margin-bottom: 11px;
}
.el-table {
  min-height: 50% !important;
}
.always_handerOne {
  height: 80px;
  background-color: #ffffff;
  // border-radius: 14px;
}
.always_handerOne1 {
  height: auto;
  background-color: #ffffff;
  // border-radius: 14px;
  padding: 20px;
}
.always_title {
  font-size: 20px;
  font-weight: bold;
  line-height: 53px;
  margin-left: 30px;
}
.always_title1 {
  font-size: 18px;
  font-weight: bold;
  // line-height: 53px;
  margin-left: 15px;
  position: relative;
}
.always_title1 ::before {
  content: "|";
  flex-shrink: 0;
  width: 4px;
  height: 6%;
  margin-left: 12px;
  // background: #f90;
  color: #f90;
  position: absolute;
  left: -22px;
  margin-bottom: 12px;
}
.always_hander {
  background: url(../../../assets/images/header0.png);
  height: 20px;
  width: 100%;
}
.el_formContent .el-form-item {
  width: 50%;
}
.el-tree__close-btn {
  display: none;
}
</style>
